package com.yanzhen.common.aspect;

import com.alibaba.fastjson.JSON;
import com.yanzhen.common.annotation.SysLog;
import com.yanzhen.jwt.JwtUtil;
import com.yanzhen.model.Log;
import com.yanzhen.service.LogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@EnableAspectJAutoProxy
public class SysLogAspect {
    @Autowired
    LogService logService;

    @Pointcut("@annotation(com.yanzhen.common.annotation.SysLog)")
    public void logPointcut(){}

    @Around("logPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //执行的开始时间
        long begin=System.currentTimeMillis();
        Object proceed = point.proceed();
        //方法执行的时长
        long time=System.currentTimeMillis()-begin;
        //保存日志操作的信息
        saveSysLog(point,time);
        return proceed;
    }

    /**
     * 保存日志操作的相关方法
     * @param point
     */
    private void saveSysLog(ProceedingJoinPoint point,long time) {
        Log log=new Log();
        //TODO 获取当前用户和IP的信息
        //获取当前调用的方法
        MethodSignature signature= (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        //需要获取@SysLog注解的信息
        SysLog sysLogAnno = method.getAnnotation(SysLog.class);
        if (sysLogAnno!=null){
            //绑定operation的值
            log.setOperation(sysLogAnno.value());
        }
        //绑定方法的名称
        Class<?> className = point.getTarget().getClass();
        String methodName = method.getName();
        log.setMethod(className+"."+methodName+"()");

        //获取token
//        String token=request.getHeader("token");
        //获取用户名
//        String username = JwtUtil.getMemberIdByJwtToken(token);
//        log.setUsername(username);

        //绑定方法的参数
        Object[] paramArgs = point.getArgs();
        String params = JSON.toJSON(paramArgs).toString();
        log.setParams(params);

        //绑定方法调用的执行时长
        log.setTime(time);
        //绑定记录的创建时间
        log.setCreateDate(LocalDateTime.now());


        logService.save(log);
    }
}

